using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TemplateWizard;
using System.Windows.Forms;
using EnvDTE;
using System.Xml;
using SPVisualDev.VSAddin.Dialogs;
using SPVisualDev.VSAddin.Dialogs.PropertySheets;

namespace SPVisualDev.VSAddin
{
    public class NewFeatureWizard: IWizard
    {
        private DTE m_DTE;
        private string m_feature_name;

        public NewFeatureWizard()
        {
        }

        // This method is called before opening any item that 
        // has the OpenInEditor attribute.
        public void BeforeOpeningFile(ProjectItem projectItem)
        {
        }

        public void ProjectFinishedGenerating(Project project)
        {
        }

        // This method is only called for item templates,
        // not for project templates.
        public void ProjectItemFinishedGenerating(ProjectItem projectItem)
        {
        }

        // This method is called after the project is created.
        public void RunFinished()
        {
        }

        public void RunStarted(object automationObject,
            Dictionary<string, string> replacementsDictionary,
            WizardRunKind runKind, object[] customParams)
        {
            try
            {
                //System.Diagnostics.Debugger.Break();

                m_DTE = (DTE)automationObject;
                m_feature_name = replacementsDictionary["$rootname$"];

                if (m_DTE.SelectedItems.Count > 0)
                {
                    Project proj = m_DTE.SelectedItems.Item(1).Project;
                    if (proj == null)
                    {
                        proj = m_DTE.SelectedItems.Item(1).ProjectItem.ContainingProject;
                    }

                    if (proj == null)
                        throw new Exception("Could not add feature because no project was selected.");

                    ProjectItem features = Common.GetProjectItem(proj, "12\\TEMPLATE\\Features", "\\");
                    if (features != null)
                    {
                        try
                        {
                            ProjectItem feature_folder = features.ProjectItems.Item(m_feature_name);
                            throw new Exception("There is already a feature named " + m_feature_name + " in features folder.");
                        }
                        catch
                        {
                            features.ProjectItems.AddFolder(m_feature_name, Constants.vsProjectItemKindPhysicalFolder);
                            ProjectItem feature_folder = features.ProjectItems.Item(m_feature_name);


                            XmlDocument xmldoc = new XmlDocument();
                            string xml =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<Feature
	Id=""{0}"" xmlns=""http://schemas.microsoft.com/sharepoint/""
	Title=""{1}""
	Scope=""Web""
    Hidden=""False"">
</Feature>";
                            xmldoc.LoadXml(string.Format(xml, Guid.NewGuid().ToString("D").ToUpper(), m_feature_name));

                            string path = Common.GetProjectItemPath(feature_folder) + "\\Feature.xml";
                            xmldoc.Save(path);

                            feature_folder.ProjectItems.AddFromFile(path);

                            try
                            {
                                AddIn addin = m_DTE.AddIns.Item(typeof(Connect).FullName);
                                SPVisualDev.VSAddin.Connect connect = addin.Object as SPVisualDev.VSAddin.Connect;

                                using (DialogFeatureEditor editor = new DialogFeatureEditor(feature_folder, connect))
                                {
                                    if (replacementsDictionary.ContainsKey("$wizarddata$"))
                                    {
                                        XmlDocument xmlFeatureType = new XmlDocument();
                                        xmlFeatureType.LoadXml(replacementsDictionary["$wizarddata$"]);

                                        string name = replacementsDictionary["$rootname$"];
                                        string featureType = xmlFeatureType.DocumentElement.InnerText;
                                        if (featureType == "ListTemplate")
                                        {
                                            CreateFeature_ListTemplate(name, editor, feature_folder);
                                        }

                                        else if (featureType == "ContentType")
                                        {
                                            CreateFeature_ContentType(name, editor, feature_folder);
                                        }

                                    }


                                    DialogResult result = editor.ShowDialog();

                                    if (result == DialogResult.OK)
                                    {
                                        connect.PushDownFiles(feature_folder, false);
                                    }
                                }

                            }
                            catch (Exception ex)
                            {
                                DialogError.ShowError(ex, "Error running feature editor.", false);
                            }

                        }
                    }
                }

            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        // This method is only called for item templates,
        // not for project templates.
        public bool ShouldAddProjectItem(string filePath)
        {
            return true;
        }

        private void CreateFeature_ListTemplate(string Name, DialogFeatureEditor featureEditor, ProjectItem FeatureFolderItem)
        {
            ElementInfo elementInfo = featureEditor.FeatureManager.AddElement(null, "<ListTemplate/>");
            elementInfo.New = true;
            elementInfo.NewElementFileName = Common.FilterIllegalCharsInFileName(Name) + ".xml";

            PropSheetListTemplate propSheet = new PropSheetListTemplate(featureEditor.DefaultResourceFile, FeatureFolderItem, elementInfo);
            propSheet.SetNewSheetFlag(true);
            propSheet.DisplayName = new ResourceStringContainer(Name, featureEditor.DefaultResourceFile, FeatureFolderItem);
            propSheet.Name = Name;

            featureEditor.AddElementToContainingList(propSheet);
        }

        private void CreateFeature_ContentType(string Name, DialogFeatureEditor featureEditor, ProjectItem FeatureFolderItem)
        {
            ElementInfo elementInfo = featureEditor.FeatureManager.AddElement(null, "<ContentType/>");
            elementInfo.New = true;
            elementInfo.NewElementFileName = Common.FilterIllegalCharsInFileName(Name) + ".xml";

            PropSheetContentType propSheet = new PropSheetContentType(featureEditor.DefaultResourceFile, FeatureFolderItem, elementInfo, featureEditor.Project);
            propSheet.SetNewSheetFlag(true);
            propSheet.Name = new ResourceStringContainer(Name, featureEditor.DefaultResourceFile, FeatureFolderItem);

            featureEditor.AddElementToContainingList(propSheet);
        }

    }
}

